package com.wonder.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.domain.SysFile;
import com.wonder.admin.mapper.SysUploadConfigDao;
import com.wonder.admin.service.SysFileService;
import com.wonder.app.domain.Tuopanbinding;
import com.wonder.app.domain.WorkSetting;
import com.wonder.app.service.ExcuteService;
import com.wonder.app.service.TuopanbindingService;
import com.wonder.app.service.TuopancoolService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.service.*;

import cn.hutool.json.JSONException;
import com.wonder.app.domain.WorkSetting;
import com.wonder.common.config.WonderConfig;
import com.wonder.common.utils.file.FileUploadUtils;
import com.wonder.common.utils.file.FileUtils;
import com.wonder.common.utils.file.MimeTypeUtils;
import com.wonder.common.utils.file.OSSServiceUtil;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import com.wonder.framework.aws.service.AwsS3Service;
import io.netty.handler.codec.base64.Base64Decoder;
import org.bouncycastle.util.test.TestResult;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import com.wonder.app.domain.Excute;
import com.wonder.app.domain.Tuopanbinding;
import com.wonder.app.domain.Tuopancool;
import com.wonder.app.domain.Worktest;
import com.wonder.app.mapper.ExcuteDao;
import com.wonder.app.mapper.TuopanbindingDao;
import com.wonder.app.mapper.TuopancoolDao;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

/**
 * 接受者客户端回调
 */
@Component
public class MqttReceiveCallBack implements MqttCallback {
    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，可重连");
        MqttData.mqttData.mqttReceiveConfig.connect();
        System.out.println("连接成功");
    }

    /**
     * 消息到达的回调
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println("servicemqtt1");
        System.out.println(String.format("接收消息主题 : %s",topic));
        System.out.println(String.format("接收消息Qos : %d",message.getQos()));
        System.out.println(String.format("接收消息内容 : %s",new String(message.getPayload())));
        System.out.println(String.format("接收消息retained : %b",message.isRetained()));
        //订阅托盘绑定信息
        if(topic.toString().contains("awf_info_binding/")) {
            JSONObject jsonObject = new JSONObject(message.getPayload());
            String s = jsonObject.toString();
            // HashMap<String,String> map = JSON.parseObject(strMsg, HashMap.class);
            awfinfobinding(s,topic);
        }
            //订阅波形烧录&驱动板状态更新
        if(topic.toString().contains("awf_driver_state/")){
            String strMsg = new String(message.getPayload());
            awfdriverstate(strMsg,topic);
        }
            //订阅托盘状态(信息绑定)
        if (topic.toString().contains("awf_tray_state/")){
            String strMsg = new String(message.getPayload());
            awftratstate(strMsg,topic);
        }
        //订阅任务状态
        if (topic.toString().contains("awf_test_task_state/")){
            String strMsg = new String(message.getPayload());
            awftesttaskstate(strMsg,topic);
        }
        //订阅任务状态
        if (topic.toString().contains("awf/test/data/state")){
            String strMsg = new String(message.getPayload());
            awftesttaskstate(strMsg,topic);
        }
        //订阅测试结果
        if (topic.toString().contains("awf_test_data/")){
            String strMsg = new String(message.getPayload());
            awftestdata(strMsg,topic);
        }
        //订阅Vcom值
        if (topic.toString().contains("awf_vcom_set/")){
            String strMsg = new String(message.getPayload());
            awfvcom(strMsg,topic);
        }
        //订阅Vs值
        if (topic.toString().contains("awf_vs_set/")){
            String strMsg = new String(message.getPayload());
            awfvs(strMsg,topic);
        }
    }

    /**
     * 消息接收成功的回调
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println(String.format("接收消息成功"));
    }

    /**
     * 工单号查询,根据工单号返回工单状态,VS值和vcom值
     * @param billNo 工单号
     */
    private void workOrder(String billNo){
        VtuzxMap data = new VtuzxMap();
        //判断工单号对应的工单是否存在
        WorkSetting workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno", "JHGD240115141322209"));
        if (workSetting == null){
            data.append("FPROMPT","当前工单号不存在");
            JSONObject jsonObject = new JSONObject(data);
            MqttData.mqttData.mqttProviderConfig.publish(1,false,"awf_test_info",jsonObject.toString());
            return;
        }
        //ceshi
        Integer fvs = workSetting.getFvs();
        Integer fvcom = workSetting.getFvcom();
        data.append("FVS",fvs)
                .append("FVCOM",fvcom);
        JSONObject jsonObject = new JSONObject(data);
        MqttData.mqttData.mqttProviderConfig.publish(1,false,"awf_test_info",jsonObject.toString());
        System.out.println("");

    }

    /**
     * 解决在MqttReceiveCallBack中无法对数据库进行操作的问题
     */

    /**
     * 调用方法
     */
    @Component
    public static class MqttData {
        @Autowired
        private WorkSettingDao workSettingDao;
        @Autowired
        private TuopanbindingService tuopanbindingService;
        @Autowired
        private TuopanbindingDao tuopanbindingDao;
        @Autowired
        private TuopancoolService tuopancoolService;
        @Autowired
        private TuopancoolDao tuopancoolDao;
        @Autowired
        private ExcuteDao excuteDao;
        @Autowired
        private ExcuteService excuteService;
        @Autowired
        private MqttProviderConfig mqttProviderConfig;
        @Autowired
        private WorkSettingService workSettingService;
        @Autowired
        private WorktestDao worktestDao;
        @Autowired
        private WorktestService worktestService;
        @Autowired
        private  WorkvsDao workvsDao;
        @Autowired
        private  WorkvsService workvsService;
        @Autowired
        private  TestResultListDao testResultListDao;
        @Autowired
        private TestResultListService testResultListService;
        @Autowired
        private TestresultService testresultService;
        @Autowired
        private TestresultDao testresultDao;

        @Autowired
        private OSSServiceUtil ossServiceUtil;

        @Autowired
        private AwsS3Service awsS3Service;

        @Autowired
        private SysFileService sysFileService;

        @Autowired
        private TuopanService tuopanService;

        @Autowired
        private MqttReceiveConfig mqttReceiveConfig;

        @Autowired
        private WenduDao wenduDao;

        @Autowired
        private WenduService wenduService;

        private static MqttData mqttData;//必须重写一下
        @PostConstruct
        public void init(){
            mqttData = this;
            mqttData.workSettingDao = this.workSettingDao;
            mqttData.tuopanbindingDao = this.tuopanbindingDao;
            mqttData.tuopanbindingService = this.tuopanbindingService;
            mqttData.tuopancoolDao = this.tuopancoolDao;
            mqttData.tuopancoolService = this.tuopancoolService;
            mqttData.excuteDao = this.excuteDao;
            mqttData.excuteService = this.excuteService;
            mqttData.workSettingService = this.workSettingService;
            mqttData.worktestDao = this.worktestDao;
            mqttData.worktestService = this.worktestService;
            mqttData.workvsDao = this.workvsDao;
            mqttData.workvsService = this.workvsService;
            mqttData.testresultDao = this.testresultDao;
            mqttData.testresultService = this.testresultService;
            mqttData.testResultListService = this.testResultListService;
            mqttData.testResultListDao = this.testResultListDao;
        }

        public WorkSetting selectWorkSetting(String billNo){
            return workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",billNo));
        }
    }

    /**
     * 订阅托盘绑定信息进行存储
     * @param strMsg
     * @param topic
     */
    private void awfinfobinding(String strMsg,String topic)
    {

        //截取订阅第17位后数据作为托盘号
        String tuopan = topic.substring(17);
        //解析Json
        List<Tuopanbinding> tuopanbindingList =new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(strMsg);

            // 解析FEMBEDDEDQR数组
            JSONArray fembeddedqrArray = jsonObject.getJSONArray("FEMBEDDEDQR");
            JSONArray fepaperqrArray = jsonObject.getJSONArray("FEPAPERQR");
            // 确定循环次数，取两个数组中元素个数的最小值
//            int loopCount = Math.min(fembeddedqrArray.size(), fepaperqrArray.size());
            //确定循环次数(根据电子纸码的数量判断)
            int loopCount = fepaperqrArray.size();
            String shaoluban = "";
            String gongdanhao = "";
            String dianzizhi = "";
            // 循环解析嵌入式板和电子纸绑定信息
            for (int i = 0; i < loopCount; i++) {
                Tuopanbinding tuopanbinding1 =new Tuopanbinding();
                JSONObject fembeddedqrObject = fembeddedqrArray.getJSONObject(i);
                JSONObject fepaperqrObject = fepaperqrArray.getJSONObject(i);
                String  fepaperqr = fepaperqrObject.getStr("FEPAPERQR");//电子纸码和工单号
                if(null != fepaperqr && !"".equals(fepaperqr)){
                    shaoluban =fembeddedqrObject.getStr("FEMBEDDEDQR");//波形烧录&驱动板二维码
                    if(null != shaoluban && !"".equals(shaoluban)){
                        gongdanhao = fepaperqr.substring(fepaperqr.indexOf(",") + 1);
                        dianzizhi = fepaperqr.substring(0,fepaperqr.indexOf(","));
                        tuopanbinding1.setFembeddedqr1(shaoluban);
                        tuopanbinding1.setFepaperqr1(dianzizhi);
                        tuopanbinding1.setFtuopan(tuopan);
                        tuopanbinding1.setPosition(i);
                        tuopanbinding1.setFsaleorder(gongdanhao);
                        tuopanbinding1.setIsqudong(false);
                        tuopanbindingList.add(tuopanbinding1);
                        taskdata(gongdanhao,shaoluban,dianzizhi);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断托盘之前是否绑定过数据
        List<Tuopanbinding> selectList = MqttData.mqttData.tuopanbindingDao.selectList(new QueryWrapper<Tuopanbinding>().eq("ftuopan",tuopan));
        //如果之前绑定过数据则将原数据移动至冷数据表，并添加新的数据
        if (selectList.size() > 0) {
            List<Tuopancool> tuopancoolList =new ArrayList<>();

            for (Tuopanbinding tuopanbinding:selectList) {
                Tuopancool tuopancool =new Tuopancool();
                tuopancool.setFsaleorder(tuopanbinding.getFsaleorder());
                tuopancool.setFembeddedqr1(tuopanbinding.getFembeddedqr1());
                tuopancool.setFepaperqr1(tuopanbinding.getFepaperqr1());
                tuopancool.setFtuopan(tuopanbinding.getFtuopan());
                tuopancool.setPosition(tuopanbinding.getPosition());
                tuopancool.setFtuopanbindingid(tuopanbinding.getId());
                tuopancoolList.add(tuopancool);
            }
            //将原表数据移到冷数据表
            MqttData.mqttData.tuopancoolService.saveOrUpdateBatch(tuopancoolList);
            //删除原表数据
            boolean ftuopan = MqttData.mqttData.tuopanbindingService.remove(new QueryWrapper<Tuopanbinding>().eq("ftuopan", tuopan));
            //插入表新的数据
            MqttData.mqttData.tuopanbindingService.saveOrUpdateBatch(tuopanbindingList);
        }
        else {
            MqttData.mqttData.tuopanbindingService.saveOrUpdateBatch(tuopanbindingList);
        }

    }

    /**
     * 订阅波形烧录板状态
     * @param strMsg
     * @param topic
     */
    private void awfdriverstate(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //截取订阅第14位后数据作为波形烧录以及驱动板二维码信息
        String erewima = topic.substring(17);//波形烧录以及驱动板二维码信息
        int state = json.getInt("STATE");
        //获取托盘绑定信息
        Tuopanbinding tuopanbinding = MqttData.mqttData.tuopanbindingDao.selectOne(new QueryWrapper<Tuopanbinding>().eq("fembeddedqr1",erewima));
        if (null != tuopanbinding){
            String tuopan = tuopanbinding.getFtuopan();
            String shaoluban = tuopanbinding.getFembeddedqr1();
            String dianzizhi = tuopanbinding.getFepaperqr1();
            //判断当前工单下的波形是否都烧录完毕
            String fsaleorder = tuopanbinding.getFsaleorder();//工单号
            tuopanbinding.setIsqudong(true);
            //修改驱动板的执行状态为已经执行
            MqttData.mqttData.tuopanbindingDao.updateById(tuopanbinding);

            //驱动板烧录完毕后取消订阅
            MqttData.mqttData.mqttProviderConfig.publish(1, true, "awf_task_data/"+shaoluban, "");
            //如果状态为0x01 准备完毕，等待进入温箱测试,发布任务
            if(state == 1){
                awftesttask(tuopan);
            }


        }

    }

    /**
     * 订阅托盘状态
     * @param strMsg
     * @param topic
     */
    private void awftratstate(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //截取订阅第15位后的信息作为托盘二维码
        String tuopanNo = topic.substring(15);
        Excute excute = MqttData.mqttData.excuteService.getOne(new QueryWrapper<Excute>().eq("fembeddedqr", tuopanNo));
        if (null != excute){
            //修改托盘执行状态
            String fdatetime = json.getStr("FDATETIME");
            excute.setUpdateTime(VtuzxUtil.parseDate(fdatetime));
            excute.setTrayStatus(json.getInt("FSTATE"));

            //根据托盘二维码修改托盘状态
            boolean res = MqttData.mqttData.excuteService.updateById(excute);
            if(res){
                //如果托盘状态为通电区稳定开始发布任务
                if (json.getInt("FSTATE") == 2)
                {
                    //发布托盘任务
                    awftesttask(tuopanNo);
                }
            }

        }

    }

    /**
     * 订阅任务状态
     * @param strMsg
     * @param topic
     */
    private void awftesttaskstate(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //当前日期
        Date currentDate = new Date();
        //截取topic任务id
        long taskid = Integer.parseInt(topic.substring(20));
        //任务状态
        int FSTATE = json.getInt("FSTATE");
        Excute excute = MqttData.mqttData.excuteDao.selectOne(new QueryWrapper<Excute>().eq("id",taskid));
        excute.setStatus(FSTATE);
        excute.setUpdateTime(currentDate);
        //根据id修改状态
        MqttData.mqttData.excuteService.updateById(excute);
    }

    /**
     * 订阅测试结果数据
     * @param strMsg
     * @param topic
     */
    private void awftestdata(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //当前日期
        Date currentDate = new Date();
        //截取topic电子纸码还有工单号
        String head = topic.substring(14);
        String dianzizhi = head.substring(0,head.indexOf(","));
        String gongdanhao = head.substring(head.indexOf(",") + 1);
        String tuopan = json.getStr("FBOARDQR");//托盘二维码
        String FEQUIPMENTSNUMBER = json.getStr("FEQUIPMENTSNUMBER");//设备编码
        String FTESTRESULT = json.getStr("FTESTRESULT");//设备判断结果
        JSONObject fi1val = json.getJSONObject("FI1VAL");//I1信息
        String imageStr = json.getStr("FISIMGDATABASE");//图片
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = null;
        String imageName = "";//图片名称
        String imageUrl = "";//图片路径
        //将base64图片转成byte[]
        try {
            bytes = decoder.decode(imageStr);
            for (int i = 0; i < bytes.length; i++){
                if(bytes[i] < 0 ){
                    bytes[i] += 256;
                }
            }
            MultipartFile multipartFile = FileUtils.encodeToMultipartFile(bytes);
            imageName = multipartFile.getName();
            imageUrl = uploadFile(multipartFile, "");
        } catch (Exception e){
            e.printStackTrace();
        }

        List<Map<String,Object>> imageList = new ArrayList<>();
        Map<String,Object> imageData = new HashMap<>();
        imageData.put("url",imageUrl);
        imageData.put("name",imageName);
        imageList.add(imageData);

        //查询托盘绑定信息
        Tuopanbinding tuopanbinding = MqttData.mqttData.tuopanbindingDao.selectOne(new QueryWrapper<Tuopanbinding>().eq("fepaperqr1",dianzizhi));
        //获取工单号
//        String gongdnahao = tuopanbinding.getFsaleorder();
        //嵌入式板二维码(驱动板)
        String qianrushi = tuopanbinding.getFembeddedqr1();
        //电子纸二维码
        String epaperqr = tuopanbinding.getFepaperqr1();

        //按照工单号查询数据
        WorkSetting  workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",gongdanhao));

        //大伟建表
        List<Testresult> testresultsList = new ArrayList<>();

        //保存测试结果主表
        Testresult testresults = new Testresult();
        testresults.setFbillno(gongdanhao);//工单号
        testresults.setFtray(tuopan);//托盘
        testresults.setFvc(workSetting.getFvcom());//VCOM值
        testresults.setFisvs(workSetting.getFvs());//VS值
        testresults.setFdevice(FEQUIPMENTSNUMBER);//设备
        testresults.setFqianru(qianrushi);//嵌入式板
        testresults.setFstate(FTESTRESULT);//设备判断结果
        testresults.setFepaper(epaperqr);//电子纸二维码
        testresults.setFcompletetime(currentDate);//完成时间
        testresults.setFtype("测试");//类型
        testresults.setFtupian_table(JSON.toJSONString(imageList));
        MqttData.mqttData.testresultService.save(testresults);
        //保存测试结果明细

        //获取单据头内码关联信息保存测试结果明细
        long detailid = testresults.getId();
        TestResultList testResultList = new TestResultList();
        testResultList.setFdetailid(detailid);//关联主表
        testResultList.setFqianru(qianrushi);//嵌入式板
        testResultList.setFstate(FTESTRESULT);//设备判断结果
        testResultList.setFepaper(epaperqr);//电子纸二维码
//        testResultList.setFl1(fi1val.toString());//I1信息
        testResultList.setFtupian(imageUrl);//图片
        MqttData.mqttData.testResultListService.save(testResultList);

        //收到结果后判断是否ng,如果ng的话重新发布任务(发布驱动板任务)
//        if("NG".equals(FTESTRESULT)){


        //判断是否所有温度都烧录完毕,如果没烧录完毕让设备放入通电区,
        //如果烧录完毕放到出料口

        //获取工单vs测试波形
        List<Workvs> workvsList = MqttData.mqttData.workvsDao.selectList(new QueryWrapper<Workvs>()
                .eq("fdetailid",workSetting.getId()));
//                    .eq("fiszx",0));
        if (workvsList.size() > 0){
            for (Workvs workvs : workvsList){
                String wenduNo = workvs.getFemperature();
                Wendu wendu = MqttData.mqttData.wenduDao.selectOne(new QueryWrapper<Wendu>().eq("wdbillno", wenduNo));
                int wdrangel = wendu.getWdrangel();//温度段左
                int wdranger = wendu.getWdranger();//温度右
                int excute1 = wendu.getExcute();//执行的温度
                if(excute1 >= wdrangel && excute1 <= wdranger){//放到通电口
                    VtuzxMap data = new VtuzxMap();
                    VtuzxMap task = new VtuzxMap();
                    data.append("FTASJID", "194")
                            .append("FTASK",task.append("FEMPERATURE", "")
                                    .append("FTYPE", "")
                                    .append("FSTATUS","2")
                                    .append("FRESIDTIME", ""));//存放时间)
                    JSONObject jsonObject = new JSONObject(data);
                    MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                    System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                    System.out.println(jsonObject.toString());
                    //发布驱动板任务之前修改驱动板的状态为未执行
                    List<Tuopanbinding> tuopanList = MqttData.mqttData.tuopanbindingDao.selectList(new QueryWrapper<Tuopanbinding>().eq("ftuopan", tuopan));
                    for (Tuopanbinding tuopanbinding1 : tuopanList){
                        tuopanbinding1.setIsqudong(false);
                    }
                    boolean b = MqttData.mqttData.tuopanbindingService.saveOrUpdateBatch(tuopanList);
                    taskdata(gongdanhao,qianrushi,epaperqr);//驱动板任务
                    break;
                } else {//结束任务
                    VtuzxMap data = new VtuzxMap();
                    VtuzxMap task = new VtuzxMap();
                    data.append("FTASJID", "194")
                            .append("FTASK",task.append("FEMPERATURE", "")
                                    .append("FTYPE", "")
                                    .append("FSTATUS","4")
                                    .append("FRESIDTIME", ""));//存放时间)
                    JSONObject jsonObject = new JSONObject(data);
                    MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                    System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                    System.out.println(jsonObject.toString());
                    break;
                }

            }

        }

    }




    /**
     * 订阅Vcom值
     * @param strMsg
     * @param topic
     */
    private void awfvcom(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //当前日期
        Date currentDate = new Date();
        //截取topic
        String gongdan = topic.substring(13);
        List<WorkSetting> workSettingList =new ArrayList<>();
        List<WorkSetting> updateList = new ArrayList<>();
        WorkSetting workSetting =new WorkSetting();
        //按照工单号查询数据
        workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",gongdan));
        //赋值获取到的FVCOM
        int fvs = json.getInt("FVCOM");
        workSetting.setFvcom(json.getInt("FVCOM"));
        //修改工单FVCOM值
        MqttData.mqttData.workSettingService.updateById(workSetting);
        //重新发布工单任务信息
        MqttData.mqttData.workSettingService.sendWorkMessage(workSetting);
    }

    /**
     * 修改工单VS值
     * @param strMsg
     * @param topic
     */
    private void awfvs(String strMsg,String topic){
        //转换为Json格式
        JSONObject json = new JSONObject(strMsg);
        //当前日期
        Date currentDate = new Date();
        //截取topic
        String gongdan = topic.substring(11);
        List<WorkSetting> workSettingList =new ArrayList<>();
        List<WorkSetting> updateList = new ArrayList<>();
        WorkSetting workSetting =new WorkSetting();
        //按照工单号查询数据
        workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",gongdan));
        //赋值获取到的FVS
        int fvs = json.getInt("FVS");
        workSetting.setFvs(json.getInt("FVS"));
        //修改工单FVS值
        MqttData.mqttData.workSettingService.updateById(workSetting);
        //修改成功后重新发送工单信息
        MqttData.mqttData.workSettingService.sendWorkMessage(workSetting);
    }


    /**
     * 发送任务测试任务
     * @param tuopan
     */
    private void awftesttask(String tuopan){
        //判断当前托盘绑定的驱动板是否都执行完毕
        Long aLong = MqttData.mqttData.tuopanbindingDao.selectCount(new QueryWrapper<Tuopanbinding>().eq("ftuopan", tuopan).eq("isqudong", false));
        if(aLong > 0){
            return;
        }
        //当前日期
        Date currentDate = new Date();
        List<Tuopanbinding> tuopanbindings = MqttData.mqttData.tuopanbindingDao.selectList(new QueryWrapper<Tuopanbinding>().eq("ftuopan",tuopan));
        for (Tuopanbinding tuopanbinding : tuopanbindings){
            //工单
            String gongdan = tuopanbinding.getFsaleorder();
            WorkSetting workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",gongdan));
            long id = workSetting.getId();
            long fiszx = 0;
            long taskid = 0;
            Worktest worktest = new Worktest();
            //获取工单测试波形
            List<Worktest> worktestList = MqttData.mqttData.worktestDao.selectList(new QueryWrapper<Worktest>()
                    .eq("fdetailid",id));
//                    .eq("fiszx",0));
            //获取工单vs测试波形
            List<Workvs> workvsList = MqttData.mqttData.workvsDao.selectList(new QueryWrapper<Workvs>()
                    .eq("fdetailid",id));
//                    .eq("fiszx",0));
            //先执行移到出料口
            if (worktestList.size() == 0 && workvsList.size() ==0){
                VtuzxMap data = new VtuzxMap();
                VtuzxMap task = new VtuzxMap();
                Excute excute = new Excute();
                excute.setVCom(workSetting.getFvcom());
                excute.setBillNo(gongdan);
                excute.setCreateTime(currentDate);
                excute.setFembeddedqr(tuopan);
                MqttData.mqttData.excuteService.saveOrUpdate(excute);
                taskid = excute.getId();


                //拼接任务执行
                data.append("FTASJID", taskid)
                        .append("FTASK",task.append("FEMPERATURE","")
                                .append("FTYPE", "")
                                .append("FSTATUS","4")
                                .append("FRESIDTIME",""));//存放时间
                JSONObject jsonObject = new JSONObject(data);
                MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                System.out.println(jsonObject.toString());
                break;
            }
            //测试波形
            if (worktestList.size() >0) {
                for (Worktest selectwork : worktestList) {
                    VtuzxMap data = new VtuzxMap();
                    VtuzxMap task = new VtuzxMap();
                    fiszx = selectwork.getFiszx();
                    //如果执行过
                    if (fiszx == 1) {
                        break;
                    } else {
                        Excute excute = new Excute();
                        excute.setVCom(workSetting.getFvcom());
                        excute.setBillNo(gongdan);
                        excute.setCreateTime(currentDate);
                        excute.setFembeddedqr(tuopan);
                        MqttData.mqttData.excuteService.save(excute);
                        taskid = excute.getId();
                        //拼接任务执行
                        data.append("FTASJID", taskid)
                                .append("FTASK",task.append("FEMPERATURE", selectwork.getFemperature())
                                        .append("FTYPE", "TEST")
                                        .append("FSTATUS","1")
                                        .append("FRESIDTIME", selectwork.getFresidtime()));//存放时间)
                        JSONObject jsonObject = new JSONObject(data);
                        MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                        System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                        System.out.println(jsonObject.toString());
                        //修改执行状态为已执行
                        worktest.setFiszx(1);
                        MqttData.mqttData.worktestDao.updateById(worktest);
                        break;
                    }
                }
            }
            //vs波形
            if(workvsList.size() > 0) {
                for (Workvs selectvs : workvsList) {
                    VtuzxMap data = new VtuzxMap();
                    VtuzxMap task = new VtuzxMap();
                        Excute excute = new Excute();
                        excute.setVCom(workSetting.getFvcom());
                        excute.setBillNo(gongdan);
                        excute.setCreateTime(currentDate);
                        excute.setFembeddedqr(tuopan);
                        excute.setVsCount(workSetting.getFvs());
                        MqttData.mqttData.excuteService.save(excute);
                        taskid = excute.getId();
                        String wenduNo = selectvs.getFemperature();
                        Wendu wendu = MqttData.mqttData.wenduDao.selectOne(new QueryWrapper<Wendu>().eq("wdbillno", wenduNo));
                        int wdrangel = wendu.getWdrangel();//温度段左
                        int wdranger = wendu.getWdranger();//温度右
                        int excute1 = wendu.getExcute();
                        if (excute1 >= wdrangel && excute1 <= wdranger){

                            //拼接任务执行
                            data.append("FTASJID", taskid)
                                    .append("FTASK",task.append("FEMPERATURE", excute1)
                                            .append("FTYPE", "VS")
                                            .append("FSTATUS","1")
                                            .append("FRESIDTIME", selectvs.getFresidtime()));//存放时间)
                            JSONObject jsonObject = new JSONObject(data);
                            MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                            System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                            System.out.println(jsonObject.toString());
                            //修改执行状态
                            selectvs.setFiszx(1);
                            MqttData.mqttData.workvsDao.updateById(selectvs);
                            wendu.setExcute(excute1 + 5);
                            MqttData.mqttData.wenduDao.updateById(wendu);
                            break;
                        } else if (excute1 > wdranger){
                            //拼接任务执行
                            data.append("FTASJID", taskid)
                                    .append("FTASK",task.append("FEMPERATURE", "")
                                            .append("FTYPE", "")
                                            .append("FSTATUS","4")
                                            .append("FRESIDTIME", ""));//存放时间)
                            JSONObject jsonObject = new JSONObject(data);
                            MqttData.mqttData.mqttProviderConfig.publish(1, false, "awf_test_task/"+tuopan, jsonObject.toString());
                            System.out.println(String.format("topic: %s","awf_test_task/"+tuopan));
                            System.out.println(jsonObject.toString());
                            //修改执行状态
                            selectvs.setFiszx(1);
                            MqttData.mqttData.workvsDao.updateById(selectvs);
                            break;
                        }

                }
            }
            break;
        }

    }

    /**
     * 发布驱动板任务信息
     * @param gongdanhao
     * @param shaoluban
     * @param dianzizhi
     */
    public void taskdata(String gongdanhao,String shaoluban,String dianzizhi){
        VtuzxMap data = new VtuzxMap();
        WorkSetting workSetting = MqttData.mqttData.workSettingDao.selectOne(new QueryWrapper<WorkSetting>().eq("fbillno",gongdanhao));
        //获取工单测试波形
        List<Worktest> worktestList = MqttData.mqttData.worktestDao.selectList(new QueryWrapper<Worktest>()
                .eq("fdetailid",workSetting.getId()));
//                .eq("fiszx",0));
        //获取工单vs测试波形
        List<Workvs> workvsList = MqttData.mqttData.workvsDao.selectList(new QueryWrapper<Workvs>()
                .eq("fdetailid",workSetting.getId()));
//                .eq("fiszx",0));
        if (worktestList.size()>0) {
            for (Worktest selectwork : worktestList) {
                data.append("FWAVEFORMID", selectwork.getFboxing())
                        .append("IMAGEID", selectwork.getFpicture())
                        .append("SCREENMODELID",dianzizhi)
                        .append("FREFRESHTIME",selectwork.getFrefreshtime());
                JSONObject jsonObject1 = new JSONObject(data);
                MqttData.mqttData.mqttProviderConfig.publish(1, true, "awf_task_data/"+shaoluban, jsonObject1.toString());
                MqttData.mqttData.worktestDao.updateById(selectwork);
                System.out.println(String.format("topic: %s","awf_task_data/"+shaoluban));
                System.out.println(jsonObject1.toString());
                break;
            }

        }
        if (workvsList.size() > 0){
            for (Workvs selectvs : workvsList) {
                String wenduNo = selectvs.getFemperature();
                Wendu wendu = MqttData.mqttData.wenduDao.selectOne(new QueryWrapper<Wendu>().eq("wdbillno", wenduNo));
                int wdrangel = wendu.getWdrangel();//温度段左
                int wdranger = wendu.getWdranger();//温度右
                int excute1 = wendu.getExcute();
                //判断这个温度段的温度是否都烧录完毕
                if(excute1 > wdranger){//说明烧录完毕停止循环什么也不用操作
                    break;
                } else {
                    data.append("FWAVEFORMID", selectvs.getFboxing())
                            .append("IMAGEID", selectvs.getFpicture())
                            .append("SCREENMODELID",dianzizhi)
                            .append("FREFRESHTIME",selectvs.getFrefreshtime());
                    JSONObject jsonObject1 = new JSONObject(data);
                    MqttData.mqttData.mqttProviderConfig.publish(1, true, "awf_task_data/"+shaoluban, jsonObject1.toString());
                    MqttData.mqttData.workvsDao.updateById(selectvs);
                    System.out.println(String.format("topic: %s","awf_task_data/"+shaoluban));
                    System.out.println(jsonObject1.toString());
                    break;
                }

            }
        }

    }

    /**
     * 文件上传到服务器
     * @param file
     * @param upload_config_id
     * @return
     * @throws Exception
     */
    private  String uploadFile(MultipartFile file, String upload_config_id) throws Exception
    {
        try
        {
            if (!file.isEmpty())
            {
                String fileType=file.getContentType();
                String hd5="";
                //Check the file hash, if the same file existed, then return the file path.
                if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
                    hd5=FileUtils.getMd5(file);
                    SysFile existedFile = MqttData.mqttData.sysFileService.getOne(new QueryWrapper<SysFile>().eq("hash", hd5));
                    if(existedFile!=null) return existedFile.getFilepath();
                }

                String imgUrl="";
                String uploadType= WonderConfig.getUploadType();
                switch(uploadType){
                    case "ali":
                        imgUrl = MqttData.mqttData.ossServiceUtil.uploadAliyun(file);
                        break;
                    case "aws-s3":
                        imgUrl=MqttData.mqttData.awsS3Service.upload(file);
                        break;

                    default:
                        // 上传并返回新文件名称
                        imgUrl= FileUploadUtils.upload( file);

                }

                if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
                    SysFile newFile=new SysFile();
                    newFile.setFilepath(imgUrl).setHash(hd5);
                    MqttData.mqttData.sysFileService.save(newFile);
                }

                return imgUrl;
            }
            return "system.uploadError";
        }
        catch (Exception e)
        {
            return e.getMessage();
        }
    }
}


